const express = require("express");
const userRouter = express.Router();
const pool = require("../pool.js");
// 导入生成Token的包
const jwt = require("jsonwebtoken");
// 导入全局配置文件（里面有token的密钥）
const config = require("../config.js");
// 将数据库的字段名转换为驼峰命名
const _ = require("lodash");
// 生成随机字符串uid
const uuid = require("node-uuid");

// var uid = uuid.v1();
// var uidv4 = uuid.v4();
let userCount = 0;



// 注册接口
userRouter.post("/register", (req, res) => {
  if (req.body.username.trim() === "" || req.body.password.trim() === "") {
    res.send({
      code: 400,
      message: "用户名或密码不能为空",
    });
    return;
  }
  pool.query(
    "SELECT * FROM user WHERE user_name = ?",
    [req.body.username],
    (err, results) => {
      if (err) throw err;
      if (results.length > 0) {
        res.send({
          code: 401,
          message: "用户名已存在，请重新输入",
        });
        return;
      } else {
        pool.query(
          "INSERT INTO user SET ?",
          {
            user_name: req.body.username,
            user_pwd: req.body.password,
            user_role: "normal",
            uid: uuid.v1().replace(/\-/g, ""),
          },
          (err, results) => {
            if (err) throw err;
            res.send({
              code: 200,
              message: "注册成功",
            });
          }
        );
      }
    }
  );
});

// 登录接口
userRouter.post("/login", (req, res) => {
  if (req.body.username.trim() === "" || req.body.password.trim() === "") {
    res.send({
      code: 402,
      message: "用户名或密码不能为空",
    });
    return;
  }
  pool.query(
    "SELECT * FROM user WHERE user_name = ?",
    [req.body.username],
    (err, results) => {
      if (results.length === 0) {
        res.send({
          code: 400,
          message: "账号不存在，请先注册",
        });
      } else {
        pool.query(
          "SELECT * FROM user WHERE user_name = ? AND user_pwd = ?",
          [req.body.username, req.body.password],
          (err, results, fields) => {
            if (err) throw err;
            if (results.length > 0) {
              // 在服务器端生成 Token 字符串
              const user = {
                ...results[0], // 解构用户信息
                user_pwd: "", //密码等敏感信息置空
              };
              // 对用户的信息进行加密，生成 token 字符串 jwt.sign
              const tokenStr = jwt.sign(user, config.jwtSecretKey, {
                expiresIn: config.expiresIn, //tonken 有效期
              });
              // 将数据库的字段名转换为驼峰命名
              const convertedResponse = _.mapKeys(user, (value, key) =>
                _.camelCase(key)
              );
              res.send({
                code: 200,
                data: {
                  user: convertedResponse,
                  token: tokenStr,
                },
                message: "登录成功",
              });
            } else {
              res.send({
                code: 401,
                message: "账号或者密码错误",
              });
            }
          }
        );
      }
    }
  );
});

// 获取用户信息接口
userRouter.get("/userInfo", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      // if (decoded.user_role !== "superAdmin" && decoded.user_role !== "admin") {
      //   res.send({
      //     code: 403,
      //     message: "你无权限查看用户信息，请登录管理员账号查看",
      //   });
      //   return;
      // }
      if (!req.query.userName) {
        res.send({
          code: 400,
          message: "请输入用户名",
        });
        return;
      }
      pool.query(
        "SELECT * FROM user WHERE user_name = ?",
        [req.query.userName],
        (err, results) => {
          if (err) throw err;
          let user = results[0];
          if (!user) {
            res.send({
              code: 400,
              message: "用户不存在",
            });
            return;
          }
          user = {
            ...user,
            user_pwd: "", //密码等敏感信息置空
          };
          const convertedResponse = _.mapKeys(user, (value, key) =>
            _.camelCase(key)
          );
          res.send({
            code: 200,
            data: {
              user: convertedResponse,
            },
            message: "获取用户信息成功",
          });
        }
      );
    }
  });
});

// 分页获取用户列表
userRouter.get("/userList", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      const page = Number(req.query.page) || 1; // 获取页码
      const pageSize = Number(req.query.pageSize) || 10; // 获取每页条数
      const start = (page - 1) * pageSize; // 计算起始位置
      const sql = `SELECT * FROM user LIMIT ?,?`; // 构造SQL语句
      // 获取总条数
      if (userCount === 0) {
        pool.query("SELECT COUNT(*) as total FROM user", (err, results) => {
          userCount = results[0].total; // 总条数
        });
      }
      // 获取分页数据
      pool.query(sql, [start, pageSize], (err, results) => {
        if (err) throw err;
        const pageParams = {
          page,
          pageSize,
          total: userCount,
        };
        const userList = results.map((user) => {
          user.user_pwd = ""; //密码等敏感信息置空
          const convertedResponse = _.mapKeys(user, (value, key) =>
            _.camelCase(key)
          );
          return convertedResponse;
        });
        res.send({
          code: 200,
          data: {
            userList,
            pageParams,
          },
          message: "获取用户列表成功",
        });
      });
    }
  });
});

// 设置用户权限
userRouter.post("/setRole", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      if (decoded.user_role !== "superAdmin") {
        res.send({
          code: 403,
          message: "你无权限修改用户权限，请登录超级管理员账号修改",
        });
      } else {
        const { userName, userRole } = req.body;
        if (decoded.user_name === userName) {
          res.send({
            code: 400,
            message: "不能修改自己的权限",
          });
          return;
        }
        pool.query(
          "UPDATE user SET user_role = ? WHERE user_name = ?",
          [userRole, userName],
          (err, results) => {
            if (err) throw err;
            if (results.affectedRows === 0) {
              res.send({
                code: 400,
                message: "用户不存在",
              });
            } else {
              res.send({
                code: 200,
                message: "修改用户权限成功",
              });
            }
          }
        );
      }
    }
  });
});

// 根据权限返回动态路由
userRouter.get("/getRouter", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      const { user_role } = decoded;
      if (user_role === "superAdmin") {
        res.send({
          code: 200,
          data: [
            {
              key: "/",
              label: "首页",
            },
            {
              key: "/userList",
              label: "用户管理",
              children: [
                {
                  key: "/userList",
                  label: "用户列表",
                },
                {
                  key: "/userList/accessControl",
                  label: "用户权限管理",
                },
              ],
            },
            {
              key: "/chatRoom",
              label: "聊天室",
            },
          ],
          message: "获取动态路由成功",
        });
      } else {
        res.send({
          code: 200,
          data: [
            {
              key: "/",
              label: "首页",
            },
            {
              key: "/userList",
              label: "用户管理",
              children: [
                {
                  key: "/userList",
                  label: "用户列表",
                },
              ],
            },
            {
              key: "/chatRoom",
              label: "聊天室",
            },
          ],
          message: "获取动态路由成功",
        });
      }
    }
  });
});

// 导出路由
module.exports = userRouter;
